package com.zbkj.admin.controller.publicly;

import com.zbkj.admin.annotation.CustomResponseAnnotation;
import com.zbkj.admin.service.WechatCallbackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;


/**
 * 微信小程序回调
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/publicly/wechat/mini/callback")
@Tag(name = "微信开放平台 -- 小程序回调")
@CustomResponseAnnotation
public class WechatCallbackController {

    @Autowired
    private WechatCallbackService wechatCallbackService;

    // 配置与公众号后台一致的 Token
    private static final String TOKEN = "ATnPNrJ72QYiNtuO7O4bFDo8POaoWj4O";

    /**
     * 验证微信服务器配置
     * @param signature 微信加密签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串
     */
    @GetMapping("/wechat")
    public String validateServer(
            @RequestParam(name = "signature", required = false) String signature,
            @RequestParam(name = "timestamp", required = false) String timestamp,
            @RequestParam(name = "nonce", required = false) String nonce,
            @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("WeChat validation request - signature: {}, timestamp: {}, nonce: {}",
                signature, timestamp, nonce);
        // 1. 校验参数是否存在
        if (signature == null || timestamp == null || nonce == null || echostr == null) {
            return "Invalid request parameters";
        }

        // 2. 生成签名
        String generatedSignature = generateSignature(timestamp, nonce);

        // 3. 签名比对
        if (signature.equals(generatedSignature)) {
            return echostr; // 返回 echostr 表示验证成功
        } else {
            return "Signature verification failed";
        }
    }

    /**
     * 生成签名
     */
    private String generateSignature(String timestamp, String nonce) {
        // a. 将 token、timestamp、nonce 按字典序排序
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);

        // b. 拼接字符串
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        String combined = sb.toString();

        // c. SHA1 加密
        return DigestUtils.sha1Hex(combined);
    }

    /**
     * 小程序回调-自己模拟
     */
    @Operation(summary = "小程序回调-自己模拟")
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test(@RequestBody String request) {
        return wechatCallbackService.callback(request);
    }

    /**
     * 小程序回调
     * 目前只用于视频号直播
     */
    @Operation(summary = "小程序回调")
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public String webHook(@RequestBody String request) {
       return wechatCallbackService.callback(request);
    }

    /**
     * 微信推送地址验证
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @param echostr 随机字符串
     */
    @RequestMapping(value = { "/index" }, method = RequestMethod.GET)
    private void webHook(
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "echostr") String echostr,
            HttpServletResponse response) throws IOException {
        System.out.println("微信小程序回调测试成功");
        PrintWriter writer = response.getWriter();
        writer.print(echostr);
        writer.flush();
        writer.close();
    }
}



